//
//  YCRSAKey.m
//  YCSchool
//
//  Created by gmall on 16/5/20.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//

#import "YCRSAKey.h"

@implementation YCRSAKey

+ (SecKeyRef)RSAPublicKeyWithDerPath:(NSString *)path
{
    NSData *certData = [NSData dataWithContentsOfFile:path];
    
    SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certData);
    SecKeyRef key = NULL;
    SecTrustRef trust = NULL;
    SecPolicyRef policy = NULL;
    if (cert != NULL) {
        policy = SecPolicyCreateBasicX509();
        if (policy) {
            if (SecTrustCreateWithCertificates((CFTypeRef)cert, policy, &trust) == noErr) {
                SecTrustResultType result;
                if (SecTrustEvaluate(trust, &result) == noErr) {
                    key = SecTrustCopyPublicKey(trust);
                }
            }
        }
    }
    if (policy) CFRelease(policy);
    if (trust) CFRelease(trust);
    if (cert) CFRelease(cert);
    
    return key;
}

+ (SecKeyRef)YCSchoolRSAPublicKey
{
    SecKeyRef _IMRSAPublicKey = [self RSAPublicKeyWithDerPath:[[NSBundle mainBundle] pathForResource:@"ycschool_rsa_public_key" ofType:@"der"]];
    return _IMRSAPublicKey;
}

+ (SecKeyRef)IMRSAPublicKey
{
    //static SecKeyRef _IMRSAPublicKey;
    //static dispatch_once_t onceToken;
    //dispatch_once(&onceToken, ^{
    SecKeyRef    _IMRSAPublicKey = [self RSAPublicKeyWithDerPath:[[NSBundle mainBundle] pathForResource:@"im_rsa_public_key" ofType:@"der"]];
    //});
    return _IMRSAPublicKey;
}

+ (SecKeyRef)commonPublicKey
{
    //    static SecKeyRef _commonPublicKey;
    //    static dispatch_once_t onceToken;
    //    dispatch_once(&onceToken, ^{
    SecKeyRef  _commonPublicKey = [self RSAPublicKeyWithDerPath:[[NSBundle mainBundle] pathForResource:@"gxin_public_key" ofType:@"der"]];
    // });
    return _commonPublicKey;
}

@end
